<?php
/**
 * @version 1.0 对象存储相关逻辑类
 * @internal
 * @link
 * @property
 * @see
 * @since
 * @uses
 *
 */
namespace app\user\logic;
use app\Api;
use xmpush\Sender;
use xmpush\Builder;
use xmpush\Constants;
use xmpush\TargetedMessage;
use xmpush\IOSBuilder;

vendor('MiPush.php.sdk.autoload');

class Push extends Api
{
    private static $obj = null;

    private $__config;

    public function __construct()
    {
        parent::__construct();
        $this->__config = config('mipush');
    }

    /**
     * 类入口
     * @return Push|null
     */
    public static function getInstance()
    {
        if (is_null(self::$obj))
            self::$obj = new self();
        return self::$obj;
    }

    public function sendPush($aliasList, $title, $desc, $payload)
    {
        $android_res = $this->android($aliasList, $title, $desc, $payload);

        $ios_res = $this->ios($aliasList, $desc, $payload);

        if (($android_res['code'] == 0) || $ios_res['code'] == 0) return true;
        
        return false;
    }

    public function android($aliasList, $title, $desc, $payload)
    {
        $secret = $this->__config['android_secret'];
        $package = $this->__config['package'];

// 常量设置必须在new Sender()方法之前调用
        Constants::setPackage($package);
        Constants::setSecret($secret);

        $sender = new Sender();

        // message1 演示自定义的点击行为
        $message = new Builder();
        $message->title($title);  // 通知栏的title
        $message->description($desc); // 通知栏的descption
        $message->passThrough(0);  // 这是一条通知栏消息，如果需要透传，把这个参数设置成1,同时去掉title和descption两个参数
        $message->payload($payload); // 携带的数据，点击后将会通过客户端的receiver中的onReceiveMessage方法传入。
        $message->extra(Builder::notifyForeground, 1); // 应用在前台是否展示通知，如果不希望应用在前台时候弹出通知，则设置这个参数为0
        $message->notifyId(2); // 通知类型。最多支持0-4 5个取值范围，同样的类型的通知会互相覆盖，不同类型可以在通知栏并存
        $message->build();
        $targetMessage = new TargetedMessage();
        $targetMessage->setTarget('alias1', TargetedMessage::TARGET_TYPE_ALIAS); // 设置发送目标。可通过regID,alias和topic三种方式发送
        $targetMessage->setMessage($message);
        return $sender->sendToAliases($message, $aliasList)->getRaw();
    }

    public function ios($aliasList, $desc, $payload)
    {
        $secret = $this->__config['ios_secret'];
        $bundleId = $this->__config['package'];

        Constants::useSandbox();
        Constants::setBundleId($bundleId);
        Constants::setSecret($secret);

        $message = new IOSBuilder();
        $message->description($desc);
        $message->soundUrl('default');
        $message->badge('4');
        $message->extra('payload', $payload);
        $message->build();

        $sender = new Sender();
        return $sender->sendToAliases($message, $aliasList)->getRaw();
    }
}
